<template>
	<view class="wrap">
		<!-- 添加顶部标签切换 -->
		<view class="tabs-box">
			<view class="tabs">
				<view v-for="(item, index) in tabsList" :key="index" class="tab-item"
					:class="{'tab-item--active': currentTab === index}" @tap="switchTab(index,item.value)">
					{{ item.label }}
				</view>
			</view>
		</view>

		<!-- 订单列表内容 -->
		<view class="order-list">
			<view class="content" v-for="(item,index) in orderList" :key="index">
				<!-- 店铺信息 -->
				<view class="shop-info">
					<view class="shop-left" @tap="goToShopDetail(item.shopDetail)">
						<image class="shop-avatar" :src="item.shopDetail.image" mode="aspectFill"></image>
						<view class="shop-name-box">
							<text class="shop-name">{{item.shopDetail.shopName}}</text>
							<u-icon name="arrow-right" color="#999" size="28"></u-icon>
						</view>
					</view>
					<view class="order-status">{{item.status}}</view>
				</view>

				<!-- 商品列表 -->
				<view class="goods-list">
					<view class="goods-item" v-for="(item1,index1) in item.orderDetails" :key="index1"
						v-show="item1.type==0" @click="orderDetail(item)">
						<image class="goods-image" :src="item1.image" mode="aspectFill"></image>
					</view>
				</view>

				<!-- 订单信息 -->
				<view class="order-info">
					<view class="order-time">{{item.orderTime}}</view>
					<view class="order-bottom">
						<view class="total">共{{item.totalNumber}}件商品 实付：
							<text class="price">¥{{item.amount || item.totalAmount}}</text>
						</view>
						<!-- 按钮区域 -->
						<view class="btn-group">
							<view class="btn" v-if="item.status == '待接单'" @click="closeOrder(item)">
								申请退款
							</view>
							<view class="btn agin" v-if="item.status === '已完成'" @click="oneMore(item)">再来一单</view>
							<view class="btn primary" v-if="item.status === '待付款'" @click="goPay(item)">去付款</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加加载状态提示 -->
		<view class="loading-text" v-if="loading">
			正在加载更多...
		</view>
		<view class="loading-text" v-if="!hasMore && orderList.length > 0">
			没有更多数据了
		</view>

		<!-- 添加取消订单弹出框 -->
		<u-popup v-model="showCancelPopup" mode="bottom" height="60%" border-radius="14">
			<view class="cancel-popup">
				<view class="popup-title">请选择取消原因</view>

				<!-- 快捷标签 -->
				<view class="cancel-tags">
					<view v-for="(tag, index) in cancelReasons" :key="index" class="tag-item"
						:class="{'tag-item--active': selectedReason === tag}" @tap="selectReason(tag)">
						{{ tag }}
					</view>
				</view>

				<!-- 自定义输入 -->
				<view class="custom-input">
					<view class="input-title">其他原因</view>
					<u-input type="textarea" v-model="customReason" placeholder="请输入取消原因（选填）" height="100"></u-input>
				</view>

				<!-- 按钮 -->
				<view class="popup-btns">
					<view class="btn cancel" @tap="showCancelPopup = false">取消</view>
					<view class="btn confirm" @tap="submitCancel">确定</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getOrderList,
		againOrder,
		cancelOrder
	} from "@/request/API.js";
	import {
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				tabsList: [{
					label: '全部',
					value: "1,2,3,4,5,6,7"
				}, {
					label: '进行中',
					value: "2,3,4"
				}, {
					label: '已完成',
					value: "5"
				}, {
					label: '退款',
					value: '7'
				}],
				currentTab: 0,
				// orderlist
				orderList: [],
				size: 10, // 每次查询多少条数据
				total: 0, // 总页数
				loading: false, // 是否正在加载
				hasMore: true, // 是否还有更多数据
				current: 1, // 当前页码
				showCancelPopup: false, // 控制弹出框显示
				cancelReasons: [
					'订单信息填写错误',
					'等待时间太长',
					'商家联系我取消',
					'我不想要了',
					'重新下单',
					'其他原因'
				],
				selectedReason: '', // 选中的原因
				customReason: '', // 自定义原因
				currentOrder: null, // 当前操作的订单
			}
		},
		async onLoad() {
			await this.refreshPage();
		},
		methods: {
			async getData(val) {
				if (!this.hasMore || this.loading) return;

				this.loading = true;
				try {
					const {
						data
					} = await getOrderList({
						current: this.current,
						status: val,
						size: this.size
					});
					// 如果是第一页，直接替换数据
					if (this.current === 1) {
						this.orderList = data.records;
					} else {
						// 否则追加数据
						this.orderList = [...this.orderList, ...data.records];
					}

					// 判断是否还有更多数据
					this.hasMore = this.current < data.pages;
					if (this.hasMore) {
						this.current++;
					}
				} catch (error) {
					console.error(error);
				} finally {
					this.loading = false;
				}
			},
			async switchTab(index, value) {
				if (this.currentTab === index) return;
				this.currentTab = index;
				await this.refreshPage();
			},
			async refreshPage() {
				this.current = 1;
				this.hasMore = true;
				this.orderList = [];
				await this.getData(this.tabsList[this.currentTab].value);
			},
			// orderdetail
			orderDetail(val) {
				this.$store.commit('setOrderInfoId', val.id)
				this.$store.commit('setSelCurrent', val.seatStatus)
				uni.navigateTo({
					url: "/subPack/order/orderDetail"
				})
			},
			// 再来一单
			async oneMore(order) {
				await againOrder(order.id)
				this.$store.commit('setSubCurrent', order.seatStatus);
				uni.navigateTo({
					url: "/subPack/index/indexSettlement"
				})
			},
			// 取消订单
			async closeOrder(order) {
				this.currentOrder = order;
				this.showCancelPopup = true;
				this.selectedReason = '';
				this.customReason = '';
			},
			// 选择取消原因
			selectReason(reason) {
				this.selectedReason = reason;
			},
			// 提交取消
			async submitCancel() {
				if (!this.selectedReason) {
					this.$u.toast('请选择取消原因');
					return;
				}

				try {
					const reason = this.customReason ?
						`${this.selectedReason}：${this.customReason}` :
						this.selectedReason;

					await cancelOrder({
						id: this.currentOrder.id,
						cancelReason: reason
					});

					this.showCancelPopup = false;
					this.$u.toast('订单取消成功');
					// 刷新订单列表
					this.refreshPage();
				} catch (error) {
					this.$u.toast('取消订单失败');
				}
			},
			// 去支付
			goPay(order) {
				console.log(order);
			},
			// 添加触底加载方法
			onReachBottom() {
				if (this.hasMore) {
					this.getData(this.tabsList[this.currentTab].value);
				}
			},
			// 添加跳转到店铺详情的方法
			goToShopDetail(shopDetail) {
				this.$store.commit('setShopDetail', shopDetail); // 存储店铺信息
				uni.navigateTo({
					url: '/subPack/shop/shopDetail'
				});
			},
		},
		// 添加页面触底监听
		onReachBottom() {
			// 提前两个卡片的高度触发加载
			const query = uni.createSelectorQuery().in(this);
			query.select('.content').boundingClientRect(data => {
				if (!data) return;
				const cardHeight = data.height;
				const windowHeight = uni.getSystemInfoSync().windowHeight;
				const scrollTop = data.top;

				// 当距离底部两个卡片高度时触发加载
				if (scrollTop + cardHeight * 2 >= windowHeight) {
					this.onReachBottom();
				}
			}).exec();
		},
		onUnload() {
			// 移除事件监听
			uni.$off('couponSelected');
		}
	}
</script>

<style lang="scss">
	.wrap {
		background-color: #f5f5f5;
		min-height: 100vh;

		.tabs-box {
			position: sticky;
			top: 0;
			z-index: 99;
			background-color: #fff;

			.tabs {
				display: flex;
				justify-content: space-around;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f3f4f6;

				.tab-item {
					position: relative;
					padding: 0 20rpx;
					color: #666;
					font-size: 28rpx;

					&--active {
						color: #EE2F37;
						font-weight: bold;

						&::after {
							content: '';
							position: absolute;
							left: 50%;
							bottom: -20rpx;
							transform: translateX(-50%);
							width: 40rpx;
							height: 4rpx;
							background-color: #EE2F37;
							border-radius: 2rpx;
						}
					}
				}
			}
		}

		.order-list {
			padding: 20rpx;

			.content {
				margin-bottom: 20rpx;
				background: #fff;
				border-radius: 16rpx;
				box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
				overflow: hidden;

				.shop-info {
					padding: 24rpx;
					border-bottom: 1rpx solid #f5f5f5;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.shop-left {
						display: flex;
						align-items: center;
						flex: 1;
						margin-right: 20rpx;
						cursor: pointer;

						.shop-avatar {
							width: 60rpx;
							height: 60rpx;
							border-radius: 8rpx;
							margin-right: 16rpx;
							flex-shrink: 0;
						}

						.shop-name-box {
							display: flex;
							align-items: center;
							flex: 1;
							min-width: 0;

							.shop-name {
								font-size: 28rpx;
								font-weight: bold;
								margin-right: 8rpx;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								max-width: 300rpx;
							}
						}
					}

					.order-status {
						font-size: 24rpx;
						color: #999;
						flex-shrink: 0;
					}
				}

				.goods-list {
					padding: 24rpx;
					background: #fafafa;
					white-space: nowrap;

					.goods-item {
						display: inline-block;
						margin-right: 16rpx;

						&:last-child {
							margin-right: 0;
						}

						.goods-image {
							width: 160rpx;
							height: 160rpx;
							border-radius: 12rpx;
						}
					}
				}

				.order-info {
					padding: 24rpx;
					border-top: 1rpx solid #f5f5f5;

					.order-time {
						font-size: 24rpx;
						color: #999;
						margin-bottom: 16rpx;
					}

					.order-bottom {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.total {
							font-size: 28rpx;
							color: #666;

							.price {
								font-size: 32rpx;
								font-weight: bold;
								color: #333;
							}
						}

						.btn-group {
							display: flex;
							gap: 20rpx;

							.btn {
								padding: 12rpx 32rpx;
								font-size: 26rpx;
								border-radius: 32rpx;
								background: #fff;
								border: 2rpx solid #ddd;

								&.primary {
									background: #EE2F37;
									color: #fff;
									border: none;
								}

								&.agin {
									color: #EE2F37;
									border-color: #EE2F37;
								}

								&+.btn {
									margin-left: 16rpx;
								}
							}
						}
					}
				}
			}
		}

		.loading-text {
			text-align: center;
			padding: 20rpx;
			color: #999;
			font-size: 24rpx;
		}

		.cancel-popup {
			padding: 30rpx;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				text-align: center;
				margin-bottom: 40rpx;
			}

			.cancel-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.tag-item {
					padding: 20rpx 30rpx;
					background: #f5f5f5;
					border-radius: 32rpx;
					font-size: 26rpx;
					color: #666;

					&--active {
						background: #fef0f0;
						color: #EE2F37;
					}
				}
			}

			.custom-input {
				margin-top: 40rpx;

				.input-title {
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 20rpx;
				}
			}

			.popup-btns {
				display: flex;
				gap: 20rpx;
				margin-top: 40rpx;

				.btn {
					flex: 1;
					text-align: center;
					padding: 20rpx 0;
					border-radius: 32rpx;
					font-size: 28rpx;

					&.cancel {
						background: #f5f5f5;
						color: #666;
					}

					&.confirm {
						background: #EE2F37;
						color: #fff;
					}
				}
			}
		}
	}
</style>